package com.example.sy4;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    protected static final int CHANG_UI = 0;
    protected static final int ERROR = 1;
    private TextView tvCity;
    private TextView tvWeather;
    private TextView tvTemp;
    private TextView tvWind;
    private TextView tvPm;
    private ImageView ivIcon;
    private int clickCount = 0;
    private List<Map<String,String>> list;

    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == CHANG_UI) {
                @SuppressLint("HandlerLeak") List<WeatherInfo> lstWeather = (List<WeatherInfo>)msg.obj;
                if (clickCount<lstWeather.size()) {
                    WeatherInfo objWI = lstWeather.get(clickCount);
                    refreshUI(objWI);
                    clickCount++;
                }
                if (clickCount == lstWeather.size())
                    clickCount = 0;
                Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
            } else if (msg.what == ERROR) {
                Toast.makeText(MainActivity.this, "获取网络数据失败",
                        Toast.LENGTH_SHORT).show();
            }
        }
    };

    private void refreshUI(WeatherInfo objInfo){
        if(objInfo!=null){
            tvCity.setText(objInfo.getCity());
            tvWeather.setText(objInfo.getWeather());
            tvTemp.setText(objInfo.getTemp());
            tvWind.setText(objInfo.getWind());
            tvPm.setText(objInfo.getPm());
            String strWeather=objInfo.getWeather();
            if(strWeather.contains("晴转多云"))
                ivIcon.setImageResource(R.drawable.cloud_sun);
            else if(strWeather.contains("多云"))
                ivIcon.setImageResource(R.drawable.clouds);
            else
                ivIcon.setImageResource(R.drawable.sun);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        InitView();
        try {
            InputStream is=this.getResources().openRawResource(R.raw.weather);
            List<WeatherInfo> weatherInfos=WeatherService.getInfsFromXML(is);
            list = new ArrayList<>();
            for (WeatherInfo info:weatherInfos){
                Map<String, String> map = new HashMap<>();
                map.put("temp",info.getTemp());
                map.put("weather",info.getWeather());
                map.put("name",info.getName());
                map.put("pm",info.getPm());
                map.put("wind",info.getWind());
                list.add(map);
            }
        } catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this,"解析信息失败",Toast.LENGTH_SHORT).show();
        }
        getMap(1,R.drawable.sun);
    }

    private void InitView() {
        tvCity = (TextView) findViewById(R.id.tv_city);
        tvWeather = (TextView) findViewById(R.id.tv_weather);
        tvTemp = (TextView) findViewById(R.id.tv_temp);
        tvWind = (TextView) findViewById(R.id.tv_wind);
        tvPm = (TextView) findViewById(R.id.tv_pm);
        ivIcon = (ImageView) findViewById(R.id.iv_icon);
        findViewById(R.id.btn_sh).setOnClickListener(this);
        findViewById(R.id.btn_gz).setOnClickListener((View.OnClickListener) this);
        findViewById(R.id.btn_bj).setOnClickListener((View.OnClickListener) this);

        final String strURL ="http://192.168.0.118:8080/weather/weather.json";
        findViewById(R.id.btn_refresh).setOnClickListener(v -> getWeatherInfo(strURL));
    }
    @SuppressLint("NonConstantResourceId")
    public void onClick(View v){
        switch (v.getId()){
            case R.id.btn_sh:
                getMap(0,R.drawable.cloud_sun);
                break;
            case R.id.btn_bj:
                getMap(1,R.drawable.sun);
                break;
            case R.id.btn_gz:
                getMap(2,R.drawable.clouds);
                break;
        }
    }


    public List<WeatherInfo> getInfosFromJson(InputStream is) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[4096];
        int count;
        while ((count = is.read(data, 0, 4096)) != -1)
            outStream.write(data, 0, count);
        String json = outStream.toString("utf-8");
        //使用gson库解析JSON数据
        Gson gson = new Gson();
        Type listType = new TypeToken<List<WeatherInfo>>() {
        }.getType();
        return gson.fromJson(json, listType);
    }

    public void getWeatherInfo(final String urlPath) {
//子线程请求网络,Android4.0以后访问网络不能放在主线程中
        new Thread() {
            private HttpURLConnection conn;

            public void run() {
                // 连接服务器 get 请求 获取图片
                try {
                    //创建URL对象
                    URL url = new URL(urlPath);
                    // 根据url 发送 http的请求
                    conn = (HttpURLConnection) url.openConnection();
                    // 设置请求的方式
                    conn.setRequestMethod("GET");
                    //设置超时时间
                    conn.setConnectTimeout(5000);
                    // 得到服务器返回的响应码
                    int code = conn.getResponseCode();
                    //请求网络成功后返回码是200
                    if (code == 200) {
                        //获取输入流
                        InputStream is = conn.getInputStream();
                        //解析输入流
                        List<WeatherInfo> lstWeatherInfo = getInfosFromJson(is);
                        if (lstWeatherInfo != null) {
                            //将更改主界面的消息发送给主线程
                            Message msg = new Message();
                            msg.what = CHANG_UI;
                            msg.obj = lstWeatherInfo;
                            handler.sendMessage(msg);
                        }
                    } else {
                        //返回码不等于200 请求服务器失败
                        Message msg = new Message();
                        msg.what = ERROR;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = ERROR;
                    handler.sendMessage(msg);
                }
                //关闭连接
                conn.disconnect();
            }
        }.start();
    }
    @SuppressLint("SetTextI18n")
    private void getMap(int number, int iconNumber){
        Map<String,String> cityMap=list.get(number);
        String temp = cityMap.get("temp");
        String weather = cityMap.get("weather");
        String name = cityMap.get("name");
        String pm = cityMap.get("pm");
        String wind = cityMap.get("wind");
        tvCity.setText(name);
        tvWeather.setText(weather);
        tvTemp.setText(""+ temp);
        tvWind.setText("风力："+ wind);
        tvPm.setText("pm:"+ pm);
        ivIcon.setImageResource(iconNumber);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }
}


